<script setup lang="ts" name="user">
import { ref, watch, onMounted } from "vue"
import { Search, Refresh, Delete } from "@element-plus/icons-vue"
import { usePagination } from "@/common/composables/usePagination"
import { listUser, delUser } from '@/common/apis/system/user'
import { ElMessage, ElMessageBox } from "element-plus"
import { useRouter } from "vue-router"
import EditRole from "./editRole.vue"
const router = useRouter()
import { useAutoRefresh } from "@/layouts/composables/useAutoRefresh"
const { paginationData, handleSizeChange: originHandleSizeChange, handleCurrentChange: originHandleCurrentChange } = usePagination()
const searchData = ref({
  userName: '',
  phonenumber: '',
  status: '',
  create_time: []
})
defineOptions({
  // 命名当前组件
  name: "SystemUser"
})
function handleSearchMore() {
  searchMore.value = !searchMore.value
  if (!searchMore.value) {
    resetSearch()
  }
}
// 表格数据
const tableData = ref([])
// 加载中
const loading = ref(false)
// 多选
const multipleSelection = ref([])
// 搜索表单
const searchFormRef = ref()
// 弹窗
const editRoleVisible = ref(false)
// 弹窗id
const editRoleId = ref('')
// 搜索更多
const searchMore = ref(false)
// 搜索内容
const searchKey = ref('')
// 搜索更多内容
// 关闭弹窗
const closeDialog = () => {
  editRoleVisible.value = false
}
// 搜索
const search = () => {
  getTableData()
}
// 重置
const resetSearch = () => {
  searchData.value = {
    userName: '',
    phonenumber: '',
    status: '',
    create_time: []
  }
  getTableData()
}
// 新增用户
const handleCreateTask = () => {
  router.replace('/more/system/user/create')
}
// 批量删除
const handleMoreDelete = () => {
  const ids: string[] = []
  const names: string[] = []
  multipleSelection.value.forEach((item: any) => {
    ids.push(item.userId as string)
    names.push(item.userName)
  })
  ElMessageBox.confirm(`正在删除用户：${names.join("，")}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    delUser(ids.join(',')).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
// 获取表格数据
const getTableData = () => {
  const params = {
    userName: searchData.value.userName,
    phonenumber: searchData.value.phonenumber,
    status: searchData.value.status,
    createTime: searchData.value.create_time[0],
    endTime: searchData.value.create_time[1],
    searchKey: searchKey.value,
    pageSize: 20,
    pageNum: 1,
  }
  listUser(params).then((res: any) => {
    tableData.value = res.data.rows
    paginationData.total = res.data.total
  })
}
// 挂载
onMounted(() => {
  getTableData()
})
// 选择数据
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val
}
// 分配角色
const handleEditRole = (id: any) => {
  editRoleVisible.value = true
  editRoleId.value = id
}
// 获取行键
const getRowKeys = (row: any) => {
  return row.userId
}
// 查看
const handleDetail = (id: any) => {
  router.replace({ path: '/more/system/user/detail', query: { id } })
}
// 删除
const handleDelete = (id: any, name: any) => {
  ElMessageBox.confirm(`确定要删除${name}吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    delUser(id).then(res => {
      ElMessage.success('删除成功')
      getTableData()
    })
  })
}
useAutoRefresh(getTableData)
/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], () => {
  getTableData()
})
</script>

<template>
  <div class="app-container pager-container">
    <div class="cc-search">
      <div class="cc-search-common">
        <el-input v-model="searchKey" size="large" placeholder="请输入搜索内容" class="csc-search-input" @keydown.enter="search">
          <template #append>
            <el-button :icon="Search" v-throttle="() => search()" />
          </template>
        </el-input>
        <div class="csc-more" @click="handleSearchMore">
          <span>更多</span>
          <el-icon v-if="!searchMore">
            <ArrowDown />
          </el-icon>
          <el-icon v-else>
            <ArrowUp />
          </el-icon>
        </div>
      </div>
      <div class="cc-search-common-more" v-if="searchMore">
        <el-form ref="searchFormRef" :model="searchData" :inline="true">
          <el-form-item label="用户名称">
            <el-input v-model="searchData.userName" @change="search()" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="searchData.phonenumber" @change="search()" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="用户状态">
            <el-select
              v-model="searchData.status" clearable placeholder="请选择" style="width: 240px"
              @change="search()"
            >
              <el-option label="正常" value="0" />
              <el-option label="停用" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item prop="time_range" label="时间范围">
            <el-date-picker
              v-model="searchData.create_time" type="daterange" unlink-panels range-separator="至"
              value-format="YYYY-MM-DD" start-placeholder="开始时间" end-placeholder="结束时间" @change="search()"
            />
          </el-form-item>
          <el-form-item>
            <el-button :icon="Refresh" @click="resetSearch">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div v-loading="loading" class="content-other">
      <div class="flex-between mb-main-padding">
        <div class="flex-y-center tag">
          <el-button type="primary" @click="handleCreateTask">新增用户</el-button>
          <el-button type="danger" :disabled="multipleSelection.length === 0" @click="handleMoreDelete">批量删除</el-button>
        </div>
      </div>
      <div class="cpi-content-main">
        <el-auto-resizer>
          <template #default="{ height, width }">
            <el-table ref="tableRef" v-loading="loading" :data="tableData" :height="height" :width="width"
              :row-key="getRowKeys" show-overflow-tooltip @selection-change="handleSelectionChange">
              <el-table-column type="selection" header-align="left" :reserve-selection="true" width="55" />
              <el-table-column prop="nickName" label="用户名称" header-align="left" />
              <el-table-column prop="userName" label="登录账号" header-align="left" />
              <el-table-column prop="roleName" label="角色名称" header-align="left" />
              <!-- <el-table-column prop="dept.deptName" label="部门" header-align="left" /> -->
              <el-table-column prop="phonenumber" label="手机" header-align="left" />
              <el-table-column prop="status" label="状态" header-align="left">
                <template #default="scope">
                  <span :class="scope.row.status == 0 ? 'green' : 'red'">{{ scope.row.status == 0 ? '正常' : '停用'
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间" header-align="left" width="180" />
              <el-table-column fixed="right" label="操作" align="center" width="140">
                <template #default="scope">
                  <el-space :size="12">
                    <el-link :underline="false" @click.stop="handleDetail(scope.row.userId)" title="查看">
                      <el-icon :size="18" color="#409EFF">
                        <View />
                      </el-icon>
                    </el-link>
                    <el-link :underline="false" type="danger"
                      @click.stop="handleDelete(scope.row.userId, scope.row.userName)" title="删除">
                      <el-icon :size="18">
                        <Delete />
                      </el-icon>
                    </el-link>
                    <el-link :underline="false" type="primary" @click.stop="handleEditRole(scope.row.userId)"
                      title="分配角色">
                      <img class="role-icon" src="@/common/assets/icons/jueseguanli.png" />
                    </el-link>
                  </el-space>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-auto-resizer>
      </div>
    </div>
    <div class="pager-wrapper">
      <el-pagination :layout="paginationData.layout" :page-sizes="paginationData.pageSizes"
        :total="paginationData.total" :page-size="paginationData.pageSize" :currentPage="paginationData.currentPage"
        @size-change="originHandleSizeChange" @current-change="originHandleCurrentChange" />
    </div>
    <EditRole :visible="editRoleVisible" :id="editRoleId" @closeDialog="closeDialog" />
  </div>
</template>
<style lang="scss" scoped></style>
